package com.anysoft.ui.activity.web;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.anysoft.R;
import com.anysoft.utils.NetWorkUtil;
import com.anysoft.utils.StringUtil;
import com.anysoft.utils.ToastUtil;

/**
 * Created by LiTingYao on 2018/6/16.
 */
public class DemoActivity extends AppCompatActivity {
    
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;
    public String loadUrl;
    public boolean isLoadError = false;
    public WebView mWebView;
    public ValueCallback<Uri[]> uploadMessage;

//    class JavaScriptObject1 {
//        @JavascriptInterface
//        public void uploadFileProxy(String url) {
//            LogUtil.e("上传文件的url" + url);
//            uploadUrl = url;
//            openFileChooser();
//        }
//
//
//    }
//
//    private void openFileChooser() {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("*/*");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(intent, AppConstant.REQUEST_CHOOSEFILE);
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//选择文件返回
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK) {
//            switch (requestCode) {
//                case AppConstant.REQUEST_CHOOSEFILE:
//                    Uri uri = data.getData();
//                    String chooseFilePath = FileChooseUtil.getInstance(this).getChooseFileResultPath(uri);
//                    uploadFile(chooseFilePath);
//                    ToastUtil.showShort("chooseFilePath" + chooseFilePath);
//                    break;
//            }
//        }
//    }
//
//    private void uploadFile(String chooseFilePath) {
//        if (TextUtils.isEmpty(chooseFilePath) || TextUtils.isEmpty(uploadUrl)) {
//            return;
//        }
//        File filePath = new File(chooseFilePath);
//        if (!filePath.exists()) {
//            ToastUtil.showShort("文件不存在，请修改文件路径");
//            return;
//        }
//        String fileName = filePath.getName();
//        mWebView.loadUrl("javascript:uploadCallBack('" + fileName + "')");
//
//    }
//
//    private void parseResponse(String json) {
//        ToastUtil.showShort("上传" + json);
//
//    }
    private String uploadUrl;
    private ValueCallback<Uri> mUploadMessage;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo_layout);
        mWebView = findViewById(R.id.webview);
        findViewById(R.id.tv_click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.evaluateJavascript("uploadCallBack(123)", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        ToastUtil.showShort(value);
                    }
                });
            }
        });
//        loadUrl = getIntent().getStringExtra("url");
//        loadUrl = "http://39.106.10.2:8070/mentor-h5/msMentorInfoEdit.html?isFromApp=true&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNTMxMzgwNDE3LCJleHAiOjE1MzE5ODUyMTd9.R9mlWn6SGL8FIkgpXzJVGEr7d1FYXtRCRrsRQo05qfLbMZ3qRbvRIjUgSItqNYA6sDtJRlKoAckrA3JWE6-agw&id=0f65559c-b137-4245-a323-68540fb5e2ab";
        loadUrl = "file:///android_asset/uploadFile.html";
        if (NetWorkUtil.isConnect(this)) {
            initWebViewConfig(loadUrl);
        }
        
    }

    private void initWebViewConfig(String url) {
        if (mWebView == null || StringUtil.isEmpty(url)) {
            return;
        }
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(
                    WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
//        mWebView.addJavascriptInterface(new JavaScriptObject1(), "jsInvoke");
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.loadUrl(url);
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibiltyTraversal");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    
    public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != DemoActivity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
            
        } else
            Toast.makeText(getBaseContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }
    
    private class MyWebChromeClient extends WebChromeClient {
        
        //  Android 3.0 以下
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }
        
        // Android 3.0以上
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            startActivityForResult(Intent.createChooser(i, "选择文件"), FILECHOOSER_RESULTCODE);
        }
        
        // Androi 4.4以下
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            
            Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
            // 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
            pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "*/*");
            startActivityForResult(pickIntent, FILECHOOSER_RESULTCODE);
        }
        
        //  Android 5.0以上
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            
            uploadMessage = filePathCallback;
            
            Intent intent = fileChooserParams.createIntent();
            try {
                startActivityForResult(intent, REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                return false;
            }
            return true;
        }
    }
}
